var TEEM = {

    options: {
        username:"",
        password:"",
        user: 0,
        recentPost: 0
    },

    events: function () {
        var _this = this;

        $(document).on('focus', '#userPost', function () {
            if (CKEDITOR.instances.userPost.getData().indexOf("Post Something...") != -1) {
                CKEDITOR.instances.userPost.setData('');
            }
        });

        $(document).on('blur', '#userPost', function () {
            if (CKEDITOR.instances.userPost.getData() == "") {
                CKEDITOR.instances.userPost.setData('<p style="color: #aaa">Post Something...</p>');
            }
        });

        $(document).on('click', '#postUserMsg', function () {
            _this.postUserMsg();
        });

        $(document).on('click', '#getUserDetails', function () {
            _this.options.username = $('#username').val();
            _this.options.password = $('#password').val();
            _this.getUserDetails();
        });

        $(document).on('click', '[data-logout]', function () {
            _this.logout();
        });
    },

    postUserMsg: function () {
        if (CKEDITOR.instances.userPost.getData().indexOf("Post Something...") != -1) {
            return;
        }

        var _this = this;
        var data = CKEDITOR.instances.userPost.getData();
        console.log(data);
        data = encodeURIComponent(data);
        console.log(data);

        CKEDITOR.instances.userPost.setData('<p style="color: #aaa">Post Something...</p>');

        $.ajax({
            type: "POST",
            dataType: "jsonp",
            url: 'http://teeem.co.uk/service',
            data: {
                'action': 'post',
                'content': data,
                'user': _this.options.user
            },
            success: function (data) {
                console.log('data', data);

                _this.update(false);
            }
        });
    },

    update: function (notifyFlag) {
        var _this = this;

        clearInterval(_this.updater);

        $.ajax({
            dataType: "jsonp",
            url: 'http://teeem.co.uk/service',
            data: {'action': 'feed'},
            success: function (data) {
                //console.log('data', data);

                data.result.reverse();

                for (var a in data.result) {
                    var div = $('<div/>', {
                        'data-post': data.result[a].id,
                        'html': $('[data-template=box]').html()
                    });

                    //console.log('data.result[a].id', data.result[a].id);
                    //console.log('_this.options.recentPost', _this.options.recentPost);

                    if (parseInt(_this.options.recentPost) < parseInt(data.result[a].id)) {
                        //console.log('recent post', _this.options.recentPost);
                        _this.options.recentPost = data.result[a].id;

                        div.find('.msgContent').html(decodeURIComponent(data.result[a].content));
                        div.find('.msgTitle').html(data.result[a].name);
                        div.find('.msgDate').html('posted at ' + data.result[a].date);
                        div.find('.profileImage').css({'background-image': 'url("' + data.result[a].image + '")'});
                        $('.feed').prepend(div);

                        if (notifyFlag) {
                            notify(div.find('.msgContent').text(), data.result[a].name);
                        }
                    }
                }

                _this.save();
                _this.updater = setInterval(function () {
                    _this.update(true);
                }, 3000);
            }
        });
    },

    getUserDetails:function () {
        var _this = this;
        $.ajax({
            dataType: "jsonp",
            url: 'http://teeem.co.uk/service',
            data: {
                'action': 'getUserDetails',
                'username': _this.options.username,
                'password': _this.options.password
            },
            success: function (data) {
                console.log('data', data);

                _this.options.user = data.result[0].id;
                $('#userInValid').hide();

                $('#userValid .msgTitle').html(data.result[0].name);
                $('#userValid .profileImage').css({'background-image': 'url("' + data.result[0].image + '")'});

                $('#userValid').parent().css({'height':'auto','overflow':'visible'});
            }
        });
    },

    initCK: function () {
        // Turn off automatic editor creation first.
        CKEDITOR.disableAutoInline = true;
        CKEDITOR.inline('userPost');
        userPost = CKEDITOR.instances.userPost;
        userPost.config.language = 'en';
        userPost.config.uiColor = '#ffffff';
        userPost.config.toolbar = [
            { name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline'] },
            { name: 'paragraph', items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent'] },
            { name: 'links', items: [ 'Link', 'Unlink' ] },
            { name: 'colors', items: [ 'TextColor', 'Uploadcare'] }
        ];
        $('#userValid').parent().css({'height':'0px','overflow':'hidden'});
    },

    save:function () {
        localStorage.setObject('options',this.options);
    },

    load:function () {
        if (localStorage.getObject('options')) {
            this.options = localStorage.getObject('options');
        }

    },

    logout:function () {
        this.options.username = "";
        this.options.password = "";
        this.options.user = 0;

        $('#userValid').parent().css({'height':'0px','overflow':'hidden'});
        $('#userInValid').fadeIn();
    },

    init: function (options) {
        var _this = this;
        this.load();
        this.options.recentPost = 0;
        this.initCK();
        this.events();
        this.update(false);
        if (this.options.user != 0) {
            this.getUserDetails();
        } else {
            $('#userInValid').fadeIn();
        }
    }
};

function notify(text, name) {
    var havePermission = window.webkitNotifications.checkPermission();
    if (havePermission == 0) {
        // 0 is PERMISSION_ALLOWED
        var notification = window.webkitNotifications.createNotification(
            'http://i.stack.imgur.com/dmHl0.png',
            name + ' posted a new message on TEEEM!',
            text
        );

        notification.onclick = function () {
            //window.open("http://stackoverflow.com/a/13328397/1269037");
            notification.close();
        }
        notification.show();
    } else {
        window.webkitNotifications.requestPermission();
    }
}

Storage.prototype.setObject = function(key, value) {
    this.setItem(key, JSON.stringify(value));
}

Storage.prototype.getObject = function(key) {
    var value = this.getItem(key);
    return value && JSON.parse(value);
}